<?php
/**
 * Created by fengkl
 * User: Administrator
 * Date: 2018年5月25日 10:38:27
 * 
 */

namespace app\admin\controller;

use app\common\logic\OrderLogic;
use app\common\server\OrderRecode;
use app\common\model\Order as OrderModel;
use think\Db;
use think\Container;
use PHPExcel;
use think\Session;
use PHPExcel_IOFactory;

class Order extends Common
{
    /**
     * 订单列表
     */
    public function index()
    {
        $Order = new OrderLogic;
        if (input('get.list')) {
            $this->map[] = ['a.or_num', 'like', '%'.input('get.list').'%'];
        }
        if (is_numeric(input('get.or_status'))) {
            $this->map[] = ['or_status', '=', input('get.or_status')];
        }
        if (is_numeric(input('get.ca_id'))) {
            $this->map[] = ['a.ca_id', '=', input('get.ca_id')];
        }

        if (input('get.start') && input('get.end') == "") {
            $this->map[] = ['or_add_time', '>=', input('get.start')];
        }
        if (input('get.start') == "" && input('get.end')) {
            $this->map[] = ['or_add_time', '<=', input('get.end')];
        }
        if (input('get.start') && input('get.end')) {
            $this->map[] = ['or_add_time', 'between', array(input('get.start'), input('get.end'))];
        }

        if (is_post()) {
            $rst = model('Order')->editInfo([input('post.key') => input('post.value')], ['id' => input('post.id')]);
            if ($rst) {
                return [
                    'code' => 1,
                    'msg' => '修改成功',
                    'data' => $rst,
                ];
            } 
        }

        $list = $Order->getList($this->map, $this->order, $this->size);

//        foreach ($list as $k => $v) {
//            $list[$k]['or_total'] = model('order_detail')
//                ->where('or_id',$v['id'])
//                ->value('or_pd_total');
//        }

//        halt($list);

        $this->assign(array(
            'list' => $list,
        ));

        return $this->fetch();
    }

    //修改发货状态
    public function change(){
        if (is_post()) {
            $rst = model('Order')->editInfo([input('post.key') => input('post.value')], ['id' => input('post.id')]);
            if ($rst) {
                return [
                    'code' => 1,
                    'msg' => '修改成功',
                    'data' => $rst,
                ];
            } 
        }
    }

    //删除
    public function dodelete(){
        $data = input('post.');
        $this->allDel($data);
    }
    //所有删除
    public function allDel($data)
    {
        if ($data['id']) {
            $id = $data['id'];
        } else {
            $this->error('id不存在');
        }
        if ($data['key']) {
            $key = $data['key'];
        } else {
            $this->error('数据表不存在');
        }
        $or_id = $data['id'];
        $info = model($key)->get($id);
        if ($info) {
            $or_num = model('Order')->where('id',$or_id)->value('or_num');
            $rel = model($key)->destroy($id);
            if ($rel) {
                $recode_data = session('admin');
                $info = [
                    'admin_user_id'=>$recode_data['id'],
                    'edit_order_num'=>$or_num,
                    'admin_user_name'=>$recode_data['ad_name'],
                    'admin_user_phone'=>$recode_data['ad_tel'],
                    'admin_user_identity'=>$recode_data['ro_id'],
                    'type'=>1,
                    'edit_time'=>date('Y-m-d H:i:s'),
                    'content'=>'删除订单'
                ];
                model('Recording')->insert($info);
                $this->success('删除成功');
            } else {
                $this->error('请联系网站管理员');
            }
        } else {
            $this->error('数据不存在');
        }
    }

    public function getdetail($id)
    {
        $map['or_id'] = $id;
        $list = model('OrderDetail')->detail($map);
        $addr = model('Order')->getAddr($id);
        $addr['addr_add'] = $addr['province'] . $addr['city'] . $addr['area'] . $addr['addr_detail'];
        return array(
            'list' => $list,
            'addr' => $addr,
        );
    }


    /**
     * 订单详情
     * @return mixed
     */
    public function detail($id)
    {

        $info = $this->getdetail($id);
//        halt($info);
        $this->assign($info);
        $this->assign('id',$id);
        return $this->fetch();
    }
    
    /**
     * 线下审核
     */
    public function approval($id,$tel){
        $voucher = model('Order')->where('id',$id)->value('or_voucher');
        $this->assign('tel',$tel);
        $this->assign('voucher',$voucher);
        $this->assign('id',$id);
        return $this->fetch();
    }
    //线下审核

    public function doapproval(){
        if (is_post()) {
            $Order = new OrderLogic;
            $data = input('post.');
            $where['id'] = $data['or_id'];
            $whereu['us_tel'] = $data['us_tel'];
            $or_status = model('order')->where($where)->value('or_status');
            if($or_status != 5){
                return [
                    'code' => 0,
                    'msg' => '该订单不是待审核订单',
                    ];
            }
            $arrays = $Order->getOneOrder($data['or_id']);
            $catid = $arrays[0]['ca_id'];
            foreach ($arrays as $key => $value) {
                $total = 0;
                $total  += $value['or_pd_price']*$value['or_pd_num'];
            }
            $awa =$Order->gaveAward($total,$data['or_id']);
            if ($awa['code']==0) {
                return json($awa); 
            }
            // halt($awa);
            // exit;
            $vip = model('user')->where($whereu)->value('us_level');
            $us_is_order = model('user')->where($whereu)->value('us_is_order');
            if ($us_is_order == 0) {
                $data2['us_is_order'] = 1;
                $res = model('user')->editInfo($data2, $whereu);
                if (!$res) {
                    return [
                    'code' => 0,
                    'msg' => '审核失败（用户是否首单）',
                    ];
                }
            }
            if ($total >= 499 && $vip == 0) {
                $data1['us_level'] = 2;

                $res = model('user')->editInfo($data1, $whereu);
                if (!$res) {
                    return [
                    'code' => 0,
                    'msg' => '审核失败（VIP会员激活失败）',
                    ];
                }
            }
            $data['or_status'] = 1;
            $res = model('Order')->editInfo($data, $where);
            if ($res) {
                return [
                    'code' => 1,
                    'msg' => '审核通过',
                ];
            }else{
                return [
                    'code' => 0,
                    'msg' => '审核失败',
                ];
            }
        }
       
    }

       //发货
    public function deliver($id){
        $data = model('Order')
            ->where('id',$id)
            ->field('or_express,or_express_num,or_express_content')
            ->find();
        $this->assign([
            'id'=>$id,
            'data'=>$data
        ]);
        return $this->fetch();
    }

    /**
     * 发货
     */
    public function dodeliver()
    {
        if (is_post()) {
            $data = input('post.');
            $validate = validate('Verify');
            $rel = array();
            $rstt = $validate->scene('deliver')->check($data);
            if (!$rstt) {
                $rel['code'] = 0;
                $rel['msg'] = $validate->getError();
                return $rel;
            }
            $where['id'] = $data['or_id'];
            //unset($data['or_id']);
            $or_status = model('order')->where($where)->value('or_status');
//            halt($or_status);

            // 更新物流信息
            if ($or_status ==2){
                $or_id = $data['or_id'];
                $data = [
                    'or_express'=>$data['or_express'],
                    'or_express_num' =>$data['or_express_num'],
                    'or_express_content' =>$data['or_express_content'],
                    'deliver_time'=> date('Y-m-d H:i:s')
                ];
                $updata = model('Order')->where('id',$or_id)->update($data);
                if ($updata){
                     //记录操作人信息

                    //操作订单统计
                    $recode_data = session('admin');

                    //订单号
                    $or_num = model('Order')->where('id',$or_id)->value('or_num');
                    $info = [
                        'admin_user_id'=>$recode_data['id'],
                        'edit_order_num'=>$or_num,
                        'admin_user_name'=>$recode_data['ad_name'],
                        'admin_user_phone'=>$recode_data['ad_tel'],
                        'admin_user_identity'=>$recode_data['ro_id'],
                        'type'=>1,
                        'edit_time'=>date('Y-m-d H:i:s'),
                        'content'=>'修改收货地址'
                    ];
                    model('Recording')->insert($info);
                    return ['code'=>1,'msg'=>'更新成功'];
                }

            }
            if($or_status != 1){
                return [
                    'code' => 0,
                    'msg' => '该订单不是待发货订单',
                    ];
            }
            $or_id = $data['or_id'];
            $recode_data = session('admin');
            // 订单号
            $or_num = model('Order')->where('id',$or_id)->value('or_num');

            $info = [
                'admin_user_id'=>$recode_data['id'],
                'edit_order_num'=>$or_num,
                'admin_user_name'=>$recode_data['ad_name'],
                'admin_user_phone'=>$recode_data['ad_tel'],
                'admin_user_identity'=>$recode_data['ro_id'],
                'type'=>1,
                'edit_time'=>date('Y-m-d H:i:s'),
                'content'=>'添加收货地址'
            ];
//            halt($info);
//            $order_record = new OrderRecode;
            model('Recording')->insert($info);

            $data['or_status'] = 2;

            $data['deliver_time'] = date('Y-m-d H:i:s');

//            halt($data);

            $rst = model('Order')->save($data, $where);
            if ($rst) {
                return [
                    'code' => 1,
                    'msg' => '发货成功',
                ];
            }
            return [
                    'code' => 0,
                    'msg' => '发货失败',
                ];
        }
    }

    public function excel(){//导出Excel


        $start = input('get.time_start');
        $end = input('get.time_send');
        $start_time = date("Y-m-d H:i:s",$start/1000);
        $end_time =$end!='NaN'? date("Y-m-d H:i:s",$end/1000):date('Y-m-d H:i:s');

        if (input('get.list')) {
            $this->map[] = ['a.or_num', 'like', '%'.input('get.list').'%'];
        }
        if (is_numeric(input('get.or_status'))) {
            $this->map[] = ['or_status', '=', input('get.or_status')];
        }
        if (is_numeric(input('get.ca_id'))) {
            $this->map[] = ['a.ca_id', '=', input('get.ca_id')];
        }

        if ($start && $start == "") {
            $this->map[] = ['or_add_time', '>=', $start_time];
        }
        if ($start == "" && $end) {
            $this->map[] = ['or_add_time', '<=', $end_time];
        }
        if ($start && $end) {
            $this->map[] = ['or_add_time', 'between', array($start_time, $end_time)];
        }


        $field = 'a.*, b.us_nickname, b.us_tel,c.addr_receiver,c.addr_detail,c.addr_tel';
//        $info = $ormodel->getList($map,$order,$size,$field);

       $info =  model('order')
            ->alias('a')
            ->join('user b', 'a.us_id = b.id', 'LEFT')
           ->join('user_addr c','a.addr_id = c.id', 'LEFT')
            ->field($field)
            ->where($this->map)
            ->order($this->order)
           ->select();
//halt($info);
        $xlsName  = "订单详情";
        $xlsCell  = array(
            array('or_num', '订单号'),
            array('or_status', '订单状态'),
//            array('or_pd_name', '商品名称'),
//            array('or_pd_total', '商品价格'),
            array('addr_receiver', '收货人'),
            array('addr_tel', '电话'),
            array('addr_detail', '收货地址'),
        );

        $xlsData  = array();
        // halt($info['list']);
//        unset($info['list']['total']);
        foreach ($info as $k => $v) {
            $xlsData[$k]['or_num'] = $v['or_num'];
            if ($v['or_status'] == 1) {
                $xlsData[$k]['or_status'] = '待发货';
            } elseif ($v['or_status'] == 2) {
                $xlsData[$k]['or_status'] = '待收货';
            } elseif ($v['or_status'] == 3) {
                $xlsData[$k]['or_status'] = '已收货';
            } elseif ($v['or_status'] == 4) {
                $xlsData[$k]['or_status'] = '已取消';
            }else{
                $xlsData[$k]['or_status'] = '未发起支付';
            }

//            $xlsData[$k]['or_status'] = $v['or_status'];
//            $xlsData[$k]['or_pd_name'] = $v['or_pd_name'];
//            $xlsData[$k]['or_pd_total'] = $v['or_pd_total'];
            $xlsData[$k]['addr_receiver'] = $v['addr_receiver'];
            $xlsData[$k]['addr_detail'] = $v['addr_detail'];
            $xlsData[$k]['addr_tel'] = $v['addr_tel'];
        }

        $this->exportExcel($xlsName,$xlsCell,$xlsData);

    }

    function exportExcel($expTitle,$expCellName,$expTableData){
        //include_once EXTEND_PATH.'PHPExcel/PHPExcel.php';//方法二
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
        $fileName = $expTitle.date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        $num = $dataNum + 3;
        $objPHPExcel = new PHPExcel();//方法一
        //$objPHPExcel = new \PHPExcel();//方法二
        $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
        $objPHPExcel->getActiveSheet(0)->mergeCells('A'.$num.':'.$cellName[$cellNum-1].$num);//合并单元格
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.'  表格生成时间:'.date('Y-m-d H:i:s'));
        // halt($num);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$num, '制表人:                      ' . '会计：                      ' . '出纳：                      ' . '审核：                      ');
        for($i=0;$i<$cellNum;$i++){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]);
        }
        // Miscellaneous glyphs, UTF-8
        for($i=0;$i<$dataNum;$i++){
            for($j=0;$j<$cellNum;$j++){
                $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);
            }
        }
        ob_end_clean();//这一步非常关键，用来清除缓冲区防止导出的excel乱码
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls");//"xls"参考下一条备注
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');//"Excel2007"生成2007版本的xlsx，"Excel5"生成2003版本的xls
        $objWriter->save('php://output');
        exit;
    }

}